using System;
using System.Collections.Generic;
using System.Linq;
using Apache.Cassandra;

namespace Cassandraemon
{

	public static class CqlResultExtensions
	{
		public static List<CassandraEntity<List<Column>>> ToCassandraEntiry(this CqlResult cqlResult)
		{
			if(cqlResult.Rows == null || cqlResult.Rows.Count == 0)
			{
				return new List<CassandraEntity<List<Column>>>();
			}
			
			return cqlResult.Rows
				.Select(x => 
	          		new CassandraEntity<List<Column>>
					{
						Key = x.Key,
						Data = x.Columns.Skip(1).ToList()	// first column is KEY
					})
				.ToList();
		}
		
		public static List<T> ToObjectList<T>(this CqlResult cqlResult)
		{
			return cqlResult.ToCassandraEntiry().Select(x => x.ToObject<T>()).ToList();
		}
		
		public static List<T> ToFlatNameList<T>(this CqlResult cqlResult)
		{
			return cqlResult.ToCassandraEntiry().SelectMany(x => x.ToFlatNameList<T>()).ToList();
		}
		
		public static List<T> ToFlatValueList<T>(this CqlResult cqlResult)
		{
			return cqlResult.ToCassandraEntiry().SelectMany(x => x.ToFlatValueList<T>()).ToList();
		}
		
		public static Dictionary<TKey, TValue> ToObjectDictionary<TKey, TValue>(this CqlResult cqlResult)
		{
			return cqlResult.ToCassandraEntiry().ToDictionary(x => MappingUtil.MappingValueType<TKey>(x.Key), x => x.ToObject<TValue>());
		}
		
		public static Dictionary<TKey, TValue> ToFlatDictionary<TKey, TValue>(this CqlResult cqlResult)
		{
			return cqlResult.ToCassandraEntiry().SelectMany(x => x.Data)
												.ToDictionary(x => MappingUtil.MappingValueType<TKey>(x.Name), 
				              								  y => MappingUtil.MappingValueType<TValue>(y.Value));
		}
		
		public static Dictionary<TKey, TValue> ToFlatValueKeyDictionary<TKey, TValue>(this CqlResult cqlResult)
		{
			return cqlResult.ToCassandraEntiry().SelectMany(x => x.Data)
												.ToDictionary(x => MappingUtil.MappingValueType<TKey>(x.Value), 
				              								  y => MappingUtil.MappingValueType<TValue>(y.Name));
		}
		
		public static Dictionary<TKey, List<TListItem>> ToNameListDictionary<TKey, TListItem>(this CqlResult cqlResult)
		{
			return cqlResult.ToCassandraEntiry().ToDictionary(x => MappingUtil.MappingValueType<TKey>(x.Key),
			                                                  y => y.ToFlatNameList<TListItem>());
		}
		
		public static Dictionary<TKey, List<TListItem>> ToValueListDictionary<TKey, TListItem>(this CqlResult cqlResult)
		{
			return cqlResult.ToCassandraEntiry().ToDictionary(x => MappingUtil.MappingValueType<TKey>(x.Key),
			                                                  y => y.ToFlatValueList<TListItem>());
		}
		
		
	}
}
